package com.julang.check.controller.wxpay;

import com.jpay.ext.kit.*;
import com.jpay.vo.AjaxResult;
import com.jpay.weixin.api.WxPayApi;
import com.jpay.weixin.api.WxPayApi.TradeType;
import com.jpay.weixin.api.WxPayApiConfig;
import com.jpay.weixin.api.WxPayApiConfig.PayModel;
import com.jpay.weixin.api.WxPayApiConfigKit;
import com.julang.check.bean.User;
import com.julang.check.bean.pay.PayData;
import com.julang.check.bean.pay.WxPayBean;
import com.julang.check.api.mapper.UserMapper;
import com.julang.check.utils.CommonData;
import com.julang.check.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

import static com.julang.check.utils.CommonData.ONEOFNUMBER;
import java.util.HashMap;
import java.util.Map;
/**
 * @author 赵自强
 * */
@Controller
@RequestMapping("/api/wxpay")
public class AbstractWxPayController extends AbstractWxPayApiController {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    private AjaxResult result = new AjaxResult();

    @Autowired
    WxPayBean wxPayBean;
    @Resource
    private UserMapper userMapper;
    String notifyUrl;

    @Override
    public WxPayApiConfig getApiConfig() {
        notifyUrl = wxPayBean.getDomain();
        return WxPayApiConfig.New()
                .setAppId(wxPayBean.getAppId())
                .setMchId(wxPayBean.getMchId())
                .setPaternerKey(wxPayBean.getPartnerKey())
                .setPayModel(PayModel.BUSINESSMODEL);
    }

    @RequestMapping(value = "/order_query", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result queryOrder(HttpServletRequest request, HttpServletResponse response,
                             @RequestParam("order") String order) {
        Result result = new Result();
        Map<String, String> params = new HashMap<>(5);
        params.put("appid", wxPayBean.getAppId());
        params.put("mch_id", wxPayBean.getMchId());
        params.put("nonce_str", String.valueOf(System.currentTimeMillis()));
        params.put("out_trade_no", order);
        params.put("sign", PaymentKit.createSign(params, wxPayBean.getPartnerKey()));
        String xmlResult = WxPayApi.orderQuery(false, params);
        Map<String, String> resultMap = PaymentKit.xmlToMap(xmlResult);
        result.success("", resultMap);
        return result;
    }

    /**
     * 扫码支付模式二 已测试
     */
    @RequestMapping(value = "/scanCode2", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result<String> scanCode2(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam("total_fee") String totalFee) {

        // String openId="o5NJx1dVRilQI6uUVSaBDuLnM3iM";
        Result<String> result = new Result<>();
        if (StrKit.isBlank(totalFee)) {
            result.fail(CommonData.FAIL, "支付金额不能为空", null);
            return result;
        }
        String userId = this.getUserId();
        if (PayData.haveUnusedOrderByUserId(userId)) {
            result.fail(CommonData.FAIL, "存在未支付的账单", null);
            return result;
        }
        String ip = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        String order = String.valueOf(System.currentTimeMillis());
        System.out.println("订单号：" + order);
        String money = totalFee;
        System.out.println("money:" + money);
        Map<String, String> params = WxPayApiConfigKit
                .getWxPayApiConfig()
                .setAttach("PaperKey论文服务积分充值")
                .setBody("PaperKey论文服务积分充值")
                .setSpbillCreateIp(ip)
                .setTotalFee(money)
                .setTradeType(TradeType.NATIVE)
                .setNotifyUrl(notifyUrl)
                .setOutTradeNo(order)
                .build();
        //订单生成
        String xmlResult = WxPayApi.pushOrder(false, params);
        Map<String, String> resultMap = PaymentKit.xmlToMap(xmlResult);
        String returnCode = resultMap.get("return_code");
        String returnMsg = resultMap.get("return_msg");
        if (!PaymentKit.codeIsOK(returnCode)) {
            result.fail(CommonData.FAIL, "error:" + returnMsg, null);
            return result;
        }
        String resultCode = resultMap.get("result_code");
        if (!PaymentKit.codeIsOK(resultCode)) {
            System.out.println(xmlResult);
            result.fail(CommonData.FAIL, "error:" + returnMsg, null);
            return result;
        }
        String qrCodeUrl = resultMap.get("code_url");
        PayData.createNewOrder(userId, order, totalFee, qrCodeUrl, 1);
        // 生成预付订单success
        result.setCode(CommonData.SUCCESS);
        result.setResult(true);
        result.setMessage(qrCodeUrl);
        result.setData(order);
        return result;
    }


    @RequestMapping(value = "/pay_notify", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String payNotify(HttpServletRequest request) {
        String xmlMsg = HttpKit.readData(request);
        System.out.println("支付通知结果:");
        Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
        for (String key : params.keySet()) {
            System.out.println(key + "  ： " + params.get(key));
        }
        String resultCode = params.get("result_code");
        String attach = params.get("attach");

        if (PaymentKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPaternerKey())) {
            if (("").equals(resultCode)) {
                log.warn("更新订单信息:" + attach);
                String userId = PayData.getUserIdByOrderId(params.get("out_trade_no"));
                if ( userId != null) {
                    User user = userMapper.selectById(userId);
                    float m = PayData.getMoneyByOrderId(params.get("out_trade_no"));
                    if (m != -1) {
                        user.setJifen(user.getJifen() + m);
                        userMapper.updateById(user);
                        System.out.println("微信： 更新数据库表积分选项");
                    }else {
                        System.out.println("微信： 表中没有相关订单数据");
                    }
                }
                PayData.makeOrderFinished(params.get("out_trade_no"), ONEOFNUMBER, params.get("transaction_id"),
                        params.get("openid"));
                Map<String, String> xml = new HashMap<String, String>(2);
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return PaymentKit.toXml(xml);
            }
        }
        // }

        return null;
    }

}
